// 定义UI变量
const wordEl = document.getElementById('word');
const text = document.getElementById('text');
const scoreEl = document.getElementById('score');
const timeEl = document.getElementById('time');
const settingsBtn = document.getElementById('settings-btn');
const settings = document.getElementById('settings');
const difficultySelect = document.getElementById('difficulty');
const endGameContainer = document.getElementById('end-game-container');
const finalScoreEl = document.getElementById('final-score');
const restartBtn = document.getElementById('restart-btn');

// 单词列表
const words = [
    'const', 'let', 'input', 'image', 'form', 'style', 'display',
    'container', 'element', 'class', 'document', 'background',
    'transition', 'transform', 'translate', 'border', 'radius',
    'margin', 'padding', 'select'
];

// 初始化变量
let randomWord;
let score = 0;
let time = 10;
let difficulty = localStorage.getItem('difficulty') || 'medium';
let timeInterval;

// 设置难度选择值
difficultySelect.value = difficulty;

// 初始化游戏
function init() {
    score = 0;
    time = 10;
    scoreEl.textContent = score;
    timeEl.textContent = time;
    endGameContainer.classList.add('hide');
    text.value = '';
    text.focus();
    
    // 清除之前的计时器
    if (timeInterval) {
        clearInterval(timeInterval);
    }
    
    // 开始新的计时器
    timeInterval = setInterval(updateTime, 1000);
    
    // 添加第一个单词
    addWordToDOM();
}

// 生成随机单词
function getRandomWord() {
    return words[Math.floor(Math.random() * words.length)];
}

// 添加单词到DOM
function addWordToDOM() {
    randomWord = getRandomWord();
    wordEl.textContent = randomWord;
}

// 更新分数
function updateScore() {
    score++;
    scoreEl.textContent = score;
}

// 更新时间
function updateTime() {
    time--;
    timeEl.textContent = time;

    if(time <= 0) {
        clearInterval(timeInterval);
        gameOver();
    }
}

// 游戏结束
function gameOver() {
    finalScoreEl.textContent = score;
    endGameContainer.classList.remove('hide');
}

// 事件监听

// 输入单词
text.addEventListener('input', e => {
    const insertedText = e.target.value;

    if(insertedText === randomWord) {
        addWordToDOM();
        updateScore();
        e.target.value = '';
        
        // 根据难度增加时间
        if(difficulty === 'hard') {
            time += 2;
        } else if(difficulty === 'medium') {
            time += 3;
        } else {
            time += 5;
        }
        
        updateTime();
    }
});

// 设置按钮点击
settingsBtn.addEventListener('click', () => {
    settings.classList.toggle('hide');
});

// 选择难度
difficultySelect.addEventListener('change', e => {
    difficulty = e.target.value;
    localStorage.setItem('difficulty', difficulty);
    init(); // 重新开始游戏
});

// 重新开始按钮
restartBtn.addEventListener('click', init);

// 初始化游戏
init();